package com.woniuxy.handler;

import com.woniuxy.service.Userservice;
import com.work.framework.pojo.ResultDTO;
import com.work.framework.pojo.User;
import com.work.framework.pojo.UserInfo;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(value = "用户类",tags = "用户")
@CrossOrigin
public class UserHandler {
    @Resource
    private Userservice userservice;


    //key的前缀
    public final String userKey_prefix = "user:";
    //key的后缀
    public final String userinfoKey_suffix=":info";
    //过期时间 一个小时
    public final int userKey_timeOut=60*60;


    /**
     *
     * @param account
     * @param pwd
     * @param session
     * @param request
     * @return
     */

    @PostMapping(value = "/login")
    @ApiOperation("登录")
        public String Login(String account, String pwd, HttpSession session,HttpServletRequest request) {
        String result="false";
        if (userservice.FindUserByUseraccount(account) == null) {//账号是否存在
            System.out.println("账号存在");
            return result;
        }
        User Realuser=userservice.FindUserByUseraccount(account);//真实用户
        if (pwd.equals(Realuser.getPwd())) {
            result = "success";
            request.setAttribute("session",session);
            session.setAttribute("user", Realuser);
            String key = userKey_prefix+Realuser.getUid()+userinfoKey_suffix;
            System.out.println("sessionId:"+session.getId());
            System.out.println("request:"+request.getSession().getId());
            System.out.println(result);

            if(Realuser.getRId()==1){
                return result;
            }else{
                result="success1";
                return result;
            }


        } else {
            System.out.println(result);
            return result;
        }

    }

    /**
     *
     * @param user
     * @param httpServletRequest
     * @return
     */
    @PostMapping(value = "/register")
    @ApiOperation("注册")
    public String Register(User user,String phone,HttpServletRequest httpServletRequest) {
        String reslut = "注册";
        if (userservice.FindUserByUseraccount(user.getAccount()) == null) {//用户信息不存在则注册
            userservice.AddUser(user);
            userservice.AddPhone(phone);
            reslut = "注册成功";
//            httpServletRequest.getRequestDispatcher(""); 请求转发
        }else{
            return reslut;
        }

    return reslut;
    }

    /**
     * 忘记密码，邮箱找回
     * @param request
     * @param userInfo
     * @return
     */
    @GetMapping(value = "/forget/{request}/{userInfo}")
    @ApiOperation("忘记密码")
    public Map forgetPass(@PathVariable  HttpServletRequest request,@PathVariable UserInfo userInfo) {
        String msg = "";
        Map<String, String> map = new HashMap<>();
//        if (userInfo == null) {              //用户名不存在
//            msg = "用户名为空";
//            map.put("msg", msg);
//            return map;
//        }
//        UserInfo userInfo1 = userservice.FindUserByPhone(userInfo.getPhone());
//        String email = userInfo1.getEmail();
//        if (user == null) {              //用户名不存在
//            msg = "用户名不存在,你不会忘记用户名了吧?";
//            map.put("msg", msg);
//            return map;
//        }
//        try {
//            String secretKey = UUID.randomUUID().toString();  //密钥
//            Timestamp outDate = new Timestamp(System.currentTimeMillis() + 30 * 60 * 1000);//30分钟后过期
//            long date = outDate.getTime() / 1000 * 1000;                  //忽略毫秒数
//            userService.setValidataCode(secretKey, user);
//            userService.setRegisterDate(outDate, user);
//            String key = user.getUser_account() + "$" + date + "$" + secretKey;
//            String digitalSignature = Md5Util.encodeByMd5(key);                 //数字签名
//
//            String emailTitle = "YOGA瑜伽";
//            String path = request.getContextPath();
//            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
////            String basePath = "localhost:8080/";
//            String resetPassHref = basePath + "user/reset_password?sid=" + digitalSignature + "&user_id=" + user.getUser_id();
//            String emailContent = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href=" + resetPassHref + " target='_BLANK'>点击我重新设置密码</a>" +
//                    "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";
//            MailUtils.sendMail(email, emailContent, emailTitle);
//            msg = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码";
////            logInfo(request,userName,"申请找回密码");
//        } catch (Exception e) {
//            e.printStackTrace();
//            msg = "邮箱不存在？未知错误,联系管理员吧。";
//        }
//        map.put("msg", msg);
        return map;
    }

    /**
     * 发送邮件 重置密码
     * @param sid
     * @param user_id
     * @return
     */
    @GetMapping(value = "/reset_password")
    @ApiOperation("验证成功 发送重置密码的邮件")
    public ModelAndView checkResetLink(String sid, String user_id) {
        ModelAndView model = new ModelAndView("error");
        String msg = "";
//        if (sid.equals("") || user_id.equals("")) {
//            msg = "链接不完整,请重新生成";
//            model.addObject("msg", msg);
////            logInfo(userName,"找回密码链接失效");
//            return model;
//        }
//        int user_i = Integer.valueOf(user_id);
//        User user = userService.findUserById(user_i);
//        if (user == null) {
//            msg = "链接错误,无法找到匹配用户,请重新申请找回密码.";
//            model.addObject("msg", msg);
////            logInfo(userName,"找回密码链接失效");
//            return model;
//        }
//        Timestamp outDate = userService.getRegisterDate(user);
//        if (outDate.getTime() <= System.currentTimeMillis()) {         //表示已经过期
//            msg = "链接已经过期,请重新申请找回密码.";
//            model.addObject("msg", msg);
//            //logInfo(userName,"找回密码链接失效");
//            return model;
//        }
//        String key = user.getAccount() + "$" + outDate.getTime() / 1000 * 1000 + "$" + userService.getValidataCode(user);          //数字签名
//        String digitalSignature = null;
//        try {
//            digitalSignature = Md5Util.encodeByMd5(key);
//        } catch (Exception e) {
//            System.out.println("md5加密异常");
//            e.printStackTrace();
//        }
//        System.out.println(key + "\t" + digitalSignature);
//        if (!digitalSignature.equals(sid)) {
//            msg = "链接不正确,是否已经过期了?重新申请吧";
//            model.addObject("msg", msg);
//            //logInfo(userName,"找回密码链接失效");
//            return model;
//        }
//        model.setViewName("login/resetpassword.html");  //返回到修改密码的界面
//        model.addObject("uid", user.getUser_id());
        model.addObject("这是发送消息接口");
        return model;
    }

    /**
     * 手机登陆方法
     * @param user
     * @param Sms
     * @return
     */
    @GetMapping(value = "/phonelogin/{user}/{Sms}/{ht}")
    @ApiOperation("手机登录")
    public ModelAndView phoneLogin(@PathVariable User user,@PathVariable String Sms,@PathVariable HttpServletRequest ht){
        String result = "";
        ModelAndView md = new ModelAndView();
//        User userByuserphone = um.findUserByuserphone(user.getUser_phone());
//        if(userByuserphone==null){
//            result="没有此用户";
//            md.addObject("msg",result);
//            return md;
//        }
//        if(!Sms.equals("9463")){
//            result="手机验证码错误";
//            md.addObject("msg",result);
//            return md;
//        }
//        User realUser = um.findUserByuserphone(user.getUser_phone());
//        int roleIdBYUserId = um.findRoleIdBYUserId(realUser.getUser_id());
//        HttpSession session = ht.getSession();
//        session.setAttribute("user", realUser);
//        session.setAttribute("role_id",roleIdBYUserId);
//        result = "登录成功";
//        md.addObject("msg", result);
//        if (roleIdBYUserId==3){
//            md.setViewName("homepagePc");
//        }else {
//            md.setViewName("homepageApp");
//        }
        md.addObject("手机登陆接口");
        return md;
    }


    /**
     * 重设密码
     * @param user
     * @return
     */
    @GetMapping(value = "/resetpassword/{user}")
    public ModelAndView reset(@PathVariable User user) {
        ModelAndView md = new ModelAndView();
        String result = "重置密码";
//        if (user.getUser_password().equals("")) {
//            return null;
//        }
//        int Us = userService.resetPassword(user);
//        userService.resetPassword(user);
//        if (0 != Us) {
//            result = "修改成功";
//            md.addObject("msg", result);
//            md.setViewName("login/login.html");
//            return md;
//        } else {
//            result = "修改失败";
//            md.addObject("msg", result);
//            md.setViewName("login/login.html");
//        }
        md.addObject("重置密码接口");
        return md;

    }


    /**
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/logout")
    @ApiOperation("用户注销")
    public String logout(HttpSession session) {
        String reslut = "";
        if (null == session) {
            reslut = "沒有用戶在登錄狀態， 請重新登錄";
            return reslut;
        } else {
            session.removeAttribute("user");
            reslut = "注销，即将跳转登录页面";
            return  reslut;
        }
    }

    /**
     *
     * @param uid
     * @return
     */
    @GetMapping(value = "/FindUserInfo")
    @ApiOperation("查询用户详细信息")
    public Map findUserMessage(int uid){
        if(userservice.FindUserByUid(uid)==null){
            return null;
        }
        Map<String, List> map= new HashMap<>();
        List<UserInfo> userMessage = userservice.findall(uid);
        map.put("userMessage",userMessage);
        return map;
    }

    /**
     * 查询用户
     * @param uid
     * @return
     */
    @GetMapping( "/findUser/{uid}")
    @ApiOperation("查询用户")
    public User FindUser(@PathVariable Integer uid){
        User user = userservice.FindUserByUid(uid);
        return user;
    }

    @GetMapping("/showMoney/{uid}")
    @ApiOperation("展示用户余额")
    public int ShowMoney(@PathVariable  Integer uid){
        int money = userservice.FindMoneyByUid(uid);
        return money;
    }

//    @ApiOperation(value = "设置用户头像", notes = "设置当前用户头像")
//    @PutMapping("/profiles")
//    public SystemResult setUserProfile(@RequestParam(required = true) MultipartFile profile) {
//        return userService.updUserProfile(profile);
//    }

    /**
     *
     * @param session
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/getAccount")
    @ApiOperation("获取session中的账号")
    @ApiResponse(code = 200,message = "返回用户编号")
    public Integer getUser(HttpSession session, HttpServletResponse response,HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        System.out.println("sessionID:"+session.getId());
        if (user==null){
            return null;
        }
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials","true");

        Integer uid = user.getUid();
        System.out.println("sessionID:"+session.getId());
        return uid;
    }

    /**
     * 通过uid找到user
     * @param uid
     * @return
     */
    @GetMapping("/findUsers/{uid}")
    @ApiOperation("通过uid找到user")
    public List<User> findUsers(@PathVariable("uid") List<Integer> uid){
        List<User> users = new ArrayList<>();
        for(int i=0;i<uid.size();i++){
            users.set(i,userservice.FindUserByUid(uid.get(i)));
        }
        return users;
    }

    /**
     * 通过account找到user
     * @param session
     * @return
     */
    @GetMapping( "/findUserInSession")
    @ApiOperation("查询用户")
    public Object FindUser(HttpSession session){
        return session.getAttribute("user");
    }

    /**
     * 通过账户名找user
     * @param account
     * @return
     */
    @GetMapping("/findUserByAccount")
    @ApiOperation("通过账户名找user")
    public String findUserByAc(String account){
        User user = userservice.FindUserByUseraccount(account);
        System.out.println(user.getUid());
        if (user == null){
            return "false";
        }else {
            return "success";
        }
    }

    /**
     *
     * @param
     * @return
     */
    @GetMapping("/findUserInfo/{uid}")
    @ApiOperation("通过uid找到用户详细信息")
    public UserInfo findUserinfo(@PathVariable Integer uid){
        return userservice.FindUserMessageByUid(uid);
    }

    /**
     * 查询普通用户的所有信息
     * @return
     */
    @GetMapping("/findUsersInfo")
    @ApiOperation("查询普通用户的所有信息")
    public ResultDTO findUsersInfo(){

        return new ResultDTO(0,"",userservice.findUsersInfo());
    }

    /**
     * 修改用户详细信息
     * @param userInfo
     * @return
     */
    @PostMapping("/updateUserInfo")
    @ApiOperation("修改用户详细信息")
    public String UpdateUserMessage(UserInfo userInfo){
        if(userInfo==null){
            return "没有数据";
        }else {
            userservice.changeMessage(userInfo);
            return "success";
        }
    }
    @PostMapping("/changePwd")
    @ApiOperation("修改用户密码")
    public String ChagePwd(Integer uid,String oldpwd,String newpwd){
        User Realuser=userservice.FindUserByUid(uid);
        if (Realuser==null){
            return "用户不存在";
        }else {
            if (Realuser.getPwd().equals(oldpwd)){
                Realuser.setPwd(newpwd);
                userservice.ChangPwd(Realuser);
                return "修改成功";
            }else {
                return "密码错误";
            }
        }
    }
    @GetMapping("/sms")
    @ApiOperation("手机验证")
    public String sms(HttpServletRequest request,String sms){
        String code=(String)request.getSession().getAttribute("code");
        if (code==null){
            return "验证码为空";
        }else {
            if (code.equals(sms)){
                return "success";
            }else {
                return "false";
            }
        }
    }
}






